<template>
  <el-drawer custom-class="drawer-box" v-model="drawerData.show" :title="drawerData.title" :direction="direction" :before-close="handleClose" :close-on-click-modal="false" size="30%">
    <template #title>
      <span class="drawer-title">{{ drawerData.title }}</span>
    </template>
    <div class="form-box">
      <el-form class="ruleFormRef" ref="ruleFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item :label="drawerData.userInfo.object_type == 1 ? '线索等级' : '客户阶段'" prop="cust_stage_id">
          <el-select style="width: 100%" v-model="formData.cust_stage_id" placeholder="请选择客户阶段">
            <el-option v-for="item in stageListOptList" :label="item.name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属人" prop="belong_to_work_user_id" v-if="drawerData.userInfo.object_type != 1">
          <el-select class="followSelect" popper-class="zw-hide_select_option" style="width: 100%" v-model="formData.belong_to_work_user_id" placeholder="全部" multiple @click.stop="openDepart">
            <el-option v-for="item in creators" :key="item.id" :label="item.name" :value="item.id">{{ item.name }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="跟进内容" prop="stage_content">
          <el-input v-model="formData.stage_content" :rows="5" type="textarea" maxlength="50" show-word-limit placeholder="请添加跟进记录" />
        </el-form-item>
        <ZWUpload v-if="drawerData.show" :upInfo="picInfo" @submit="getFileList" ref="emptyData" />
        <el-form-item label="客户打标" prop="cust_tag_ids" v-if="drawerData.userInfo.object_type != 1">
          <div class="tabs-box" v-if="tabs.length > 0">
            <div v-for="(item, index) in tabs" :key="index"
              >{{ item.name
              }}<el-icon @click="delTab(item)" style="font-size: 16px" class="del-icon">
                <close />
              </el-icon>
            </div>
          </div>
          <el-button @click="openBatchLabel">请选择标签</el-button>
        </el-form-item>
      </el-form>
      <div class="btn-box">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveFun">保存</el-button>
      </div>
    </div>
  </el-drawer>
  <ZWDepart ref="DepartRef" :type="1" @submit="getZWDepartData" />
  <BatchLabel ref="BatchLabelRef" @save="getLabelFun" />
</template>

<script lang="ts" setup>
  import { watch, ref, reactive } from 'vue'
  import BatchLabel from '@/components/BatchLabel.vue'
  import ZWDepart from '@/components/ZWDepart.vue'
  import ZWUpload from '@/components/ZWUpload.vue'
  import { stageList } from '@/api/customerCenter/labellagroup'
  import { addFollow, currentData } from '@/api/customerCenter'
  import { followDetail, updateFollow, getClueLevelList, addClue, editClue, viewClue } from '@/api/employe/employeetasks/taskmanage'
  import { ElForm, ElMessage } from 'element-plus'
  import { getSetionId } from '@/utils/utils'
  type FormInstance = InstanceType<typeof ElForm>
  const emit = defineEmits(['save'])
  const ruleFormRef: any = ref<FormInstance>()
  // 创建人options
  const creators = ref([])
  const DepartRef = ref(null)
  const BatchLabelRef = ref(null)
  const emptyData = ref(null)
  const tabs = ref([])
  const is_edit = ref(false)
  let drawerData = ref({
    show: false,
    title: '为客户【客户姓名/昵称】添加跟进',
    direction: 'rtl', //从右往左打开
    userInfo: {} //当前用户信息
  })
  const images = ref([])
  let formData: any = ref({})
  const initFun = () => {
    tabs.value = []
    formData.value = {
      cust_id: '', //客户id
      cust_stage_id: '', //客户阶段id
      belong_to_work_user_id: [], //归属员工id
      stage_content: '', //跟进内容
      images_codes: [], //上传图片code
      cust_tag_ids: [], //客户标签id
      images: [],
      follow_id: ''
    }
  }
  //获取跟进详情
  const getFllowDetail = (val: any, type?: any) => {
    let params = {
      follow_id: val.id
    }
    // 线索
    if (type == 1) {
      viewClue({ clue_follow_id: val.id }).then((res: any) => {
        drawerData.value.title = '编辑跟进'
        is_edit.value = true
        formData.value.follow_id = res.clue_follow_id
        formData.value.stage_content = res.content
        formData.value.cust_stage_id = res.grade_id
        formData.value.images_codes = getSetionId('code', res.attachs)
        emptyData.value.echo(res.attachs, 1)
      })
    } else {
      //客户
      followDetail(params).then((res: any) => {
        drawerData.value.title = '编辑跟进'
        is_edit.value = true
        formData.value.follow_id = res.follow_id
        formData.value.stage_content = res.follow_content
        formData.value.cust_stage_id = res.stage_id
        formData.value.belong_to_work_user_id = []
        creators.value = []
        res.work_user_id.type = 'user'
        formData.value.belong_to_work_user_id.push(res.work_user_id.id)
        creators.value.push(res.work_user_id)
        formData.value.cust_tag_ids = getSetionId('id', res.cust_tag)
        formData.value.images_codes = getSetionId('code', res.follow_url)
        tabs.value = res.cust_tag
        emptyData.value.echo(res.follow_url, 1)
        console.log(is_edit.value, '编辑跟进')
      })
    }
  }
  // 获取当前选中的员工的数据
  const getZWDepartData = (val: any) => {
    creators.value = val
    formData.value.belong_to_work_user_id = getSetionId('id', val)
  }
  // 图片上传
  const picInfo = ref({
    type: 1,
    label: '图片',
    prop: 'images',
    files: formData.value.images,
    multiple: true,
    limitSize: 2,
    limitNum: 9,
    acceptFile: '.jpg,.jpeg,.png,.JPG,.JPEG,.PNG'
  })

  // 获取上传成功的文件
  const getFileList = (data: any) => {
    console.log(data, 'data')
    formData.value.images_codes = []
    formData.value.images_codes = getSetionId('code', data)
  }

  // 关闭
  const handleClose = () => {
    drawerData.value.show = false
    // ruleFormRef.value.resetFields()
  }

  let rules: any = ref({
    cust_stage_id: { required: true, trigger: 'blur', message: '请选择客户阶段' },
    belong_to_work_user_id: { required: true, trigger: 'blur', message: '请选择归属员工' },
    stage_content: { required: true, trigger: 'blur', message: '请填写跟进内容' }
  })

  //打开新建选择人
  const openDepart = () => {
    DepartRef.value.appDialog.chooseArr = formData.value.belong_to_work_user_id || []
    DepartRef.value.departVisble = true
    DepartRef.value.appDialog.isInit = true
    DepartRef.value.appDialog.title = '选择员工'
    DepartRef.value.multiple = false
  }

  // 打开选择标签弹框
  const openBatchLabel = () => {
    BatchLabelRef.value.dialogVisible = true
    BatchLabelRef.value.hasConditiion = false
    BatchLabelRef.value.dialogData.labelChooseType = 2
    BatchLabelRef.value.chooseDataArr = tabs.value.length ? tabs.value : []
  }

  // 获取选择的标签
  const getLabelFun = (val: any) => {
    formData.value.cust_tag_ids = val.idList
    tabs.value = val.data
  }

  // 删除选中的标签
  const delTab = (val: any) => {
    tabs.value = tabs.value.filter((item: any) => {
      return item.id != val.id
    })
    formData.value.cust_tag_ids = formData.value.cust_tag_ids.filter((item: any) => {
      return item != val.id
    })
  }
  const stageListOptList = ref([]) //客户阶段字典

  // 获取客户阶段字典
  const stageListFun = () => {
    if (drawerData.value.userInfo.object_type == 1) {
      getClueLevelList().then((res: any) => {
        stageListOptList.value = res.data
      })
    } else {
      stageList({ page: 1, page_size: 99999 }).then((r: any) => {
        stageListOptList.value = r || []
        stageListOptList.value.unshift({
          id: 0,
          name: '请选择客户阶段'
        })
      })
    }
  }

  watch(
    () => drawerData.value.show,
    (val: boolean) => {
      if (val) {
        initFun()
        if (!drawerData.value.userInfo.object_id) {
          handleClose()
          ElMessage.error('当前数据异常，请稍后再试')
          return
        }
        const { object_type } = drawerData.value.userInfo
        drawerData.value.title = `为${object_type == 1 ? '线索' : '客户'}【${drawerData.value.userInfo.cust_name || ''}】添加跟进`
        formData.value.cust_id = drawerData.value.userInfo.object_id
        stageListFun()
      }
    }
  )

  // 获取上传的图片
  const getUploadData = (data: any, key: string) => {
    formData.value[key] = data[0] ? data[0].url : ''
  }

  // 保存
  const saveFun = () => {
    const { object_type } = drawerData.value.userInfo
    ruleFormRef.value.validate((valid: boolean) => {
      if (valid) {
        if (object_type == 1) {
          const { cust_id, cust_stage_id, stage_content, images_codes } = formData.value
          const params = {
            clue_id: cust_id,
            grade_id: cust_stage_id,
            content: stage_content,
            attachs: []
          }
          images_codes.map((i: any) => {
            params.attachs.push({ code: i, type: 1 })
          })
          if (!is_edit.value) {
            addClue(params).then((res: any) => {
              console.log(res, '成功')
              ElMessage.success('添加成功')
              emit('save')
              handleClose()
            })
          } else {
            params.clue_follow_id = formData.value.follow_id
            editClue(params).then((res: any) => {
              ElMessage.success('编辑成功')
              emit('save')
              handleClose()
            })
          }
        } else {
          let param = JSON.parse(JSON.stringify(formData.value))
          param.belong_to_work_user_id = param.belong_to_work_user_id[0] || ''
          if (!is_edit.value) {
            addFollow(param).then((r: any) => {
              ElMessage.success('添加成功')
              emit('save')
              handleClose()
            })
          } else {
            updateFollow(param).then((res: any) => {
              ElMessage.success('编辑成功')
              emit('save')
              handleClose()
            })
          }
        }
      }
    })
  }
  defineExpose({
    drawerData,
    getFllowDetail
  })
</script>

<style lang="scss" scoped>
  .drawer-box {
    .drawer-title {
      color: #333;
      font-weight: bold;
    }
    .form-box {
      max-height: calc(100vh - 126px);
      overflow-y: scroll;
      .ruleFormRef {
        margin-bottom: 40px;
      }
      .btn-box {
        text-align: right;
        border-top: solid 1px #eee;
        padding: 20px;
      }
    }
    .form-box::-webkit-scrollbar {
      display: none;
    }
    .tabs-box {
      margin-bottom: 7px;
      div {
        display: inline-block;
        background: #fffaf9;
        border-radius: 2px;
        border: 1px solid #ffc69e;
        justify-content: center;
        align-items: center;
        padding: 0 4px;
        line-height: 22px;
        height: 22px;
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        font-weight: 300;
        color: #ff6b00;
        margin-right: 10px;
        margin-bottom: 7px;
        .del-icon {
          margin-left: 8px;
          vertical-align: middle;
          cursor: pointer;
        }
      }
    }
  }
</style>
